import { createStore } from 'vuex'
import login from './login/login'
import system from './main/system/system'
import dashboard from './main/analysis/dashboard'
import type { IRootState } from './type'
import localCache from '@/utils/cache'

import { getPageListData } from '@/serviceapi/main/system/system'

const store = createStore({
  state(): IRootState {
    return {
      name: '',
      allDeparmentsList: [],
      allRolesList: [],
      allMenuList: []
    }
  },
  modules: { login, system, dashboard },
  actions: {
    async getInitialDataAction({ commit }) {
      //1:获取所有部门列表
      const departmentResult = await getPageListData('/department/list', {
        offset: 0,
        size: 1000
      })
      const { list: deparmentList } = departmentResult.data

      console.log('获取到的部门列表', deparmentList)
      commit('changeDepartmentList', deparmentList)
      localCache.saveAllDepartList(deparmentList)

      //2:获取所有角色列表
      const rolesResult = await getPageListData('/role/list', {
        offset: 0,
        size: 1000
      })
      const { list: rolesList } = rolesResult.data
      console.log('获取到的角色列表', rolesList)
      commit('changeRoleList', rolesList)
      localCache.saveAllRoleList(rolesList)

      const menuResult = await getPageListData('/menu/list', {
        offset: 0,
        size: 1000
      })
      const { list: menuList } = menuResult.data

      commit('changeMenuList', menuList)
      localCache.saveAllMenuList(menuList)
    }
  },
  getters: {},
  mutations: {
    changeDepartmentList(state, payload: any[] = []) {
      state.allDeparmentsList = payload || []
    },
    changeRoleList(state, payload) {
      state.allRolesList = payload || []
    },
    changeMenuList(state, payload) {
      state.allMenuList = payload || []
    }
  }
})

export function setupStore() {
  store.dispatch('login/loadLocalLogin')
}

export default store
